<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 面板区域 -->
        <el-card class="box-card" style="margin-top:20px">
            <!-- 输入框 -->
            <el-row>
                <el-col :span="12">
                    <div class="grid-content bg-purple">
                        <el-input placeholder="请输入内容" class="input-with-select" v-model="queryinfo.query" clearable @clear='getUserList'>
                            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="grid-content bg-purple-light" style="margin-left:20px">
                        <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                    </div>
                </el-col>
            </el-row>
            <!-- 表格 -->
            <div style="margin-top:20px">
                <template>
                    <el-table :data="userList" border="" style="width: 100%">
                        <el-table-column type='index'></el-table-column>
                        <el-table-column prop="create_time" label="日期" width="200">
                        </el-table-column>
                        <el-table-column prop="role_name" label="姓名" width="200">
                        </el-table-column>
                        <el-table-column prop="mobile" label="手机" width="200">
                        </el-table-column>
                        <el-table-column prop="email" label="邮箱" width="200">
                        </el-table-column>
                        <el-table-column prop="username" label="用户名" width="200">
                        </el-table-column>
                        <el-table-column prop="mg_state" label="状态" width="166">
                            <template slot-scope='scope'>
                                <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="changeStatus(scope.row)"></el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="210">
                            <template slot-scope='scope'>
                                <el-tooltip content="编辑" placement="top">
                                    <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditUser(scope.row.id)"></el-button>
                                </el-tooltip>
                                <el-tooltip content="删除" placement="top">
                                    <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUser(scope.row.id)"></el-button>
                                </el-tooltip>
                                <el-tooltip content="分配角色" placement="top">
                                    <el-button type="warning" icon="el-icon-setting" size="small" @click="showRoleDialog(scope.row)"></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </div>
            <!-- 分页 -->
            <div class="block" style="margin-top:20px">
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryinfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryinfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
            </div>
        </el-card>
        <!-- 添加用户的对话框 -->
            <div>
                <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close='closeAddDialog'>
                    <el-form ref="addFormRef" :model="addForm"  :rules="addFormRules"  label-width="100px" class="demo-ruleForm">
                        <el-form-item label="用户名" prop="username">
                            <el-input type="text" v-model="addForm.username"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="addForm.password"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input type="text" v-model="addForm.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机" prop="mobile">
                            <el-input type="text" v-model="addForm.mobile"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer" style="margin-right:12px">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="addUser">确 定</el-button>
                    </span>
                </el-dialog>
            </div>
        <!-- 编辑用户的对话框 -->
            <div>
                <el-dialog title="编辑用户" :visible.sync="EidtdialogVisible" width="50%" @close='closeEditDialog'>
                    <el-form :model="editForm"  label-width="100px" class="demo-ruleForm">
                        <el-form-item label="用户名" prop="username">
                            <el-input type="text" v-model="editForm.username" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input type="text" v-model="editForm.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机" prop="mobile">
                            <el-input type="text" v-model="editForm.mobile"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer" style="margin-right:12px">
                        <el-button @click="EidtdialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="EditUser(editForm.id)">确 定</el-button>
                    </span>
                </el-dialog>
            </div>
        <!-- 设置角色的对话框 -->
        <el-dialog
            title="分配角色"
            :visible.sync="userdialogVisible"
            width="30%">
            <div>姓名：{{userinfo.username}}</div>
            <div style="margin:10px 0">用户名称：{{userinfo.role_name}}</div>
            <template>
                <el-select v-model="selectedRoleId" placeholder="请选择">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                    </el-option>
                </el-select>
            </template>
            <span slot="footer" class="dialog-footer">
                <el-button @click="userdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRole(userinfo.id)">确 定</el-button>
            </span>
        </el-dialog>
    </div>

</template>

<script>
export default {
    data() {
        // 验证
        let checkEmail = (rule,value,callback) => {
            // \w一个数字字母下划线 \d一个数字 +1个以上 ?0或者1个 *0个以上
            let regEmail = /^\w+@\w+\.\w+$/
            if(!regEmail.test(value)) {
                // 不匹配
                return callback(new Error('邮箱格式不正确'))
            }
            return callback() // 正确
        }
        let checkMobile = (rule,value,callback) => {
            // \w一个数字字母下划线 \d一个数字 +1个以上 ?0或者1个 *0个以上 {10}10个
            let regMobile = /^1\d{10}$/
            if(!regMobile.test(value)) {
                // 不匹配
                return callback(new Error('手机格式不正确'))
            }
            return callback() // 正确
        }
        return {
            queryinfo:{query:'',pagenum:1,pagesize:2},
            userList:[],
            total:0,
            dialogVisible:false,
            addForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addFormRules:{
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 100, message: '长度至少3个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { validator : checkEmail, trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { validator : checkMobile, trigger: 'blur' }
                ]
            },
            EidtdialogVisible:false,
            editForm:{},
            userdialogVisible:false,
            userinfo:{},
            roleList:[],
            selectedRoleId:''
        }
    },
    created() {
        this.getUserList()
    },
    methods:{
        async getUserList() {
            let {data : res} = await this.$http.get('users',{params:this.queryinfo})
            if(res.meta.status != 200) return this.$message.error(res.meta.msg)
            // console.log(res)
            this.userList = res.data.users
            this.total = res.data.total
        },
        handleSizeChange(newPagesize) {
            console.log(newPagesize)
            this.queryinfo.pagesize = newPagesize
            this.getUserList()
        },
        handleCurrentChange(newPagenum) {
            console.log(newPagenum)
            this.queryinfo.pagenum = newPagenum
            this.getUserList()
        },
        async changeStatus(data) {
            // console.log(data)
            let uId = data.id
            let type = data.mg_state
            let {data : res} = await this.$http.put('users/'+ uId +'/state/'+ type)
            // console.log(res)
            if(res.meta.status != 200) return this.$message.error(res.meta.msg)

        },
        closeAddDialog() {
            // 清空
            this.$refs.addFormRef.resetFields()
        },
        addUser() {
            // 预验证
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return;
                let {data : res} = await this.$http.post('users',this.addForm)
                if(res.meta.status != 201) return this.$message.error(res.meta.msg)
                this.getUserList()
                // 关闭对话框
                this.dialogVisible = false
            })
        },
        closeEditDialog() {
            // 清空
            this.$refs.addFormRef.resetFields()  
        },
        async showEditUser(id) {
            this.EidtdialogVisible = true
            let {data : res} = await this.$http.get('users/' + id)
            if(res.meta.status != 200) return this.$message.error(res.meta.msg)
            this.editForm = res.data
        },
        async EditUser(id) {
            let {data : res} = await this.$http.put('users/' + id,this.editForm)
            if(res.meta.status != 200) return this.$message.error(res.meta.msg)
            this.getUserList()
            // 关闭对话框
            this.EidtdialogVisible = false
        },
        async deleteUser(id) {
            let {data : res} = await this.$http.delete('users/' + id)
            if(res.meta.status != 200) return this.$message.error(res.meta.msg)
            this.getUserList()
        },
        async showRoleDialog(data) {
            //分配角色显示框  
            // console.log(data)
            this.userinfo = data
            this.userdialogVisible = true
            let {data : res} = await this.$http.get('roles')
            if(res.meta.status != 200) return this.$message.error(res.meta.msg)
            this.roleList = res.data
            // console.log(res)
        },
        async setRole(id) {
            // 分配角色
            this.userdialogVisible = false
            let {data : res} = await this.$http.put(`users/${id}/rol e`,{rid:this.selectedRoleId})
            if(res.meta.status != 200) return this.$message.error(res.meta.msg)
            // console.log(res,this.selectedRoleId)
            this.$message.success('分配角色成功！')
        }
    }
}
</script>

<style lang="less" scoped>

</style>
